#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re

import jenkins  # pip install python-jenkins
import datetime, time
import requests

from javcra.common import constant


class Job():
    def __init__(self, jenkins_master, jenkins_job, jenkins_user, jenkins_passwd):
        '''
        jenkins_master ：master地址
        jenkins_job ：jenkins_job名字
        jenkins_user ：登陆账号
        jenkins_passwd ：登陆密码
        '''
        self.jenkins_master = jenkins_master
        self.jenkins_job = jenkins_job
        self.login_user = jenkins_user
        self.login_passwd = jenkins_passwd
        jkServer = jenkins.Jenkins(self.jenkins_master, self.login_user, self.login_passwd)
        self.jenkins_server = jkServer

    def build_job(self, parameters=None):
        '''
        api触发job
        return queueId : 378956
        '''
        print("build job")

        token = datetime.datetime.now().strftime('%Y%m%d_%H%M%S%f')
        # parameters = {"order_date": 2020071111, "test_locals_id_point_version": 2222}
        if parameters:  # ##带参数构建触发，参数必须是字典类型
            return self.jenkins_server.build_job(self.jenkins_job, parameters=parameters)

        return self.jenkins_server.build_job(self.jenkins_job)  ## 无参数构建触发

    def getLastJobId(self):
        '''
        role : 获取job名为job_name的job的最后次构建号
        '''
        return self.jenkins_server.get_job_info(self.jenkins_job)['lastBuild']['number']

    def getJobResultStatus(self, jobId):
        '''
        role:获取job名为job_name的job的某次构建的执行结果状态
        SUCCESS : job执行成功
        FAILURE ：job执行失败
        ABORTED ：人为结束构建
        None : 正在构建中
        '''
        while True:
            res = self.jenkins_server.get_build_info(self.jenkins_job, jobId)['result']
            if res:
                break
        print("任务构建完成")
        return res

    def getJobOutPut(self, jobname, jobId):
        output_res = self.jenkins_server.get_build_console_output(jobname, jobId)
        return output_res


if __name__ == '__main__':

    base_url = 'https://jenkins.openeuler.org'
    jenkins_user = 'tuShenmei'
    jenkins_passwd = '062725tu_TU'
    job_name = "function-item/release-manager/openeuler-202106281604/trigger0712"

    jk = Job(base_url, job_name, jenkins_user, jenkins_passwd)

    pkgs = ["dbus", "dbus-cpp", "dbus-glib", "dbus-python"]

    server = jenkins.Jenkins(base_url, username=jenkins_user, password=jenkins_passwd)
    params = {"ScanOSSAPIURL": constant.JENKINS_API_URL,
              "ScanOSSResultRepo": constant.JENKINS_SERVER_REPO,
              "action": "create",
              "obs_project": "openEuler:20.09",
              "update_dir": "update_20210630",
              "package_family": "standard",
              "pkgnamelist": ",".join(pkgs)
              }

    queue_num = jk.build_job(None)
    print(queue_num)

    resp = server.get_queue_item(queue_num)

    while True:
        if not resp.get("why"):
            break
        resp = server.get_queue_item(queue_num)
        print(resp.get("why"))

    last_job_num = jk.getLastJobId()
    print(last_job_num)
    print("job result status", jk.getJobResultStatus(last_job_num))

    output = jk.getJobOutPut(job_name, last_job_num)
    # output example: Starting building: function-item » release-manager » openeuler-202106281604 » aarch64 » 2-11 #14
    new_output = output.replace(" » ", "/").splitlines()
    print(new_output)

    job_name_id_dict = dict()
    for line in new_output:
        if "Starting building" in line:
            line_info = line.split()
            job_name = line_info[2]
            build_id = line_info[3].strip("#")
            job_name_id_dict[job_name] = build_id
    print(job_name_id_dict)
    # print(output)
